package main

import (
	"crypto/sha256"
	"encoding/hex"
	"fmt"
	"io"
	"os"
)

/**
  文件哈希-应用场合：急速上传，服务器检测你上传文件与已有的哈希一样，则说明文件没改变
*/
func hashSha256File(filePath string) (string, error) {
	var hashValue string //放回哈希字符串
	file, err := os.Open(filePath)
	if err != nil {
		return hashValue, err //返回错误，文件 打开失败，哈希为空
	}

	defer file.Close()

	myHash := sha256.New() //创建哈希算法对象
	if _, err := io.Copy(myHash, file); err != nil {
		return hashValue, err //处理拷贝错误
	}

	hashInBytes := myHash.Sum(nil)
	hashValue = hex.EncodeToString(hashInBytes) //哈希转换字符串

	return hashValue, err
}

func main() {
	filePath := "/home/yxr/go/src/study/src/main/study/encryp/md5.go"
	if hash, err := hashSha256File(filePath); err != nil {
		fmt.Printf("%s sha256 hash is:\n %s \n", filePath, err)
	} else {
		fmt.Printf("%s sha256 hash is:\n %s \n", filePath, hash)
	}

}
